package com.ruoyi.eqmonitor.config;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.DynamicTableNameInnerInterceptor;
import com.ruoyi.eqmonitor.utils.DynamicTableNameHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.*;

@Configuration
@Slf4j
public class MybatisPlusConfig {

    /**
     * 动态表名处理
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mpInterceptor = new MybatisPlusInterceptor();
        DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
        dynamicTableNameInnerInterceptor.setTableNameHandler((sql, tableName) -> {
            // 时序数据 按月分表
            if ("device_monitor_data".equals(tableName)) {
                // 取数据
                String suffix = DynamicTableNameHelper.getRequestData("table_suffix");
                // 删除
                DynamicTableNameHelper.remove();
                // 默认后缀
                if (StrUtil.isEmpty(suffix)) {
                    suffix = DateUtil.format(new Date(), "_yyyy_MM");
                }
                // 拼接
                tableName = tableName.concat(suffix);
                //tableName = "\"monitor_data\".".concat(tableName).concat(suffix);
            }
            return tableName;
        });
        mpInterceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);
        return mpInterceptor;
    }

}
